package org.opens.netty.template;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.net.InetSocketAddress;
import java.util.Scanner;

@Slf4j
public class ClientTemplate {

    public static void main(String[] args) throws InterruptedException {
        // 带有Future、Promise的类型都是和异步方法配套使用的, 用来处理结果.
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 客户端这边进行编码后, 服务端才能用该编码器对应的解码器进行解码
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                    }
                })
                // connect是一个异步非阻塞方法, 有当前线程发起, 真正的连接操作是由NioEventLoopGroup中的EventLoop进行的
                // 连接的建立是比较慢的, 需要一定时间建立连接, 但是这个方法是一个异步非阻塞方法, 虽然返回了, 但是返回后的一定时间内连接并未建立好
                .connect(new InetSocketAddress("localhost", 8080));

        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.info("client已启动.");
            }
        });

        Channel channel = channelFuture.sync().channel();
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.nextLine();
                if ("q".equals(line)) {
                    // close方法是一个异步操作
                    channel.close();
                    break;
                }
                channel.writeAndFlush(line);
            }
        }, "input").start();

        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                // 优雅的停下来-停止接受新任务, 等待把未发送的数据发完之后再将group中的EventLoop线程关闭, 不是立刻停止
                group.shutdownGracefully();
                log.info("连接已关闭");
            }
        });
    }
}
